<?php
namespace app\index\controller;

use think\Cache;
use think\Controller;
use Yansongda\Pay\Pay;
use think\Db;
use think\Exception;
use think\Log;
class Notify extends Controller
{
    //支付宝购买
    function ali_order_notify(){
        $t_alipay = [
            'app_id' => config('ali.app_id'),
            'notify_url' => config('ali.notify_url').'ali_order_notify',
            'ali_public_key'   => config('ali.ali_public_key'),
            'private_key' => config('ali.private_key'),
        ];
        $alipay = Pay::alipay($t_alipay);
//        $pid=db('notify')->insertGetId(array('return'=>json_encode(request()->param()),'pay_type'=>2,'type'=>2,'createtime'=>date('Y-m-d H:i:s'),'pid'=>0));
        db()->startTrans();
        try{
            $data = $alipay->verify(); // 是，验签就这么简单！
            db('notify')->insertGetId(array('return'=>json_encode($data),'pay_type'=>2,'type'=>2,'createtime'=>date('Y-m-d H:i:s'),'pid'=>0));
            if ($data['trade_status'] == 'TRADE_SUCCESS' || $data['trade_status'] == 'TRADE_FINISHED'){
                //支付成功
                $order_num=$data['out_trade_no'];
                $a=explode('_',$order_num);
                foreach($a as $v){
                    $len=strlen($v)+1;
                    $times=$v;
                }
                $order_num1=substr($order_num,0,-$len);
                $order=db('order')->where(array('o_order_num'=>$order_num1,'o_pay_status'=>0))->find();
                $user=db('user')->where(array('u_id'=>$order['u_id']))->find();
                if($order['o_type']==1){
                    $type='配送上门';
                }else if($order['o_type']==2){
                    $type='我要自提';
                }
                if(!empty($order)){
                    if($order['o_status']==0){
                        $res=db("order")
                            ->where(array("o_id" => $order['o_id']))
                            ->update(array("o_status" => 1,'o_pay_type'=>2,'o_pay_status'=>1,'o_pay_time'=>time()));
                        $system=db('system')->find();
                        $url=$system['order_notice'].'你有新的订单，请及时处理:'.date('Y-m-d-H:i:s',$order['o_create_time']).','.$order['o_id'].','.$user['u_store_name'].',支付宝,已支付,'.$type.','.$order['o_real_price'].'';
                        $content= file_get_contents($url);
                        db('order_log')->insert(array('o_id'=>$order['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'订单支付成功：支付宝'));
                    }else{
                        $res=db("order")
                            ->where(array("o_id" => $order['o_id']))
                            ->update(array('o_pay_type'=>2,'o_continue_pay_type'=>2,'o_pay_status'=>1,'o_pay_time'=>time()));
                        db('order_log')->insert(array('o_id'=>$order['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'订单支付成功：支付宝'));
                    }
                    if($res==false){
                        if($order['o_status']==0){
                            $res=db("order")
                                ->where(array("o_id" => $order['o_id']))
                                ->update(array("o_status" => 1,'o_pay_type'=>2,'o_pay_status'=>1,'o_pay_time'=>time()));
                            $system=db('system')->find();
                            $url=$system['order_notice'].'你有新的订单，请及时处理:'.date('Y-m-d-H:i:s',$order['o_create_time']).','.$order['o_id'].','.$user['u_store_name'].',支付宝,已支付,'.$type.','.$order['o_real_price'].'';
                            $content= file_get_contents($url);
                            db('order_log')->insert(array('o_id'=>$order['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'订单支付成功：支付宝'));
                        }else{
                            $res=db("order")
                                ->where(array("o_id" => $order['o_id']))
                                ->update(array('o_pay_type'=>2,'o_continue_pay_type'=>2,'o_pay_status'=>1,'o_pay_time'=>time()));
                            db('order_log')->insert(array('o_id'=>$order['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'订单支付成功：支付宝'));
                        }
                    }
                }else{
                    $order1['receipt_amount']=$data['receipt_amount'];
                    $order1['out_trade_no']=$data['out_trade_no'];
                    $refund =  $alipay->refund($order1);
                }
            }else{

            }
            db()->commit();
        } catch (Exception $e) {
            db()->rollback();
        }
        return $alipay->success()->send();
    }
    //微信购买
    function wechat_order_notify(){
        $t_wechat = [
            'appid' => config('wechat.appid'), // APP APPID
            'app_id' => config('wechat.app_id'), // APP APPID
            'mch_id' => config('wechat.mch_id'),
            'key' => config('wechat.key'),//支付密钥
            'notify_url' => config('wechat.notify_url').'wechat_order_notify',
            'cert_client' => config('wechat.cert_client'), // optional，退款等情况时用到
            'cert_key' => config('wechat.cert_key'),// optional，退款等情况时用到
        ];
//        $pid=db('notify')->insertGetId(array('return'=>json_encode(request()->param()),'pay_type'=>1,'type'=>2,'createtime'=>date('Y-m-d H:i:s'),'pid'=>0));
        $pay = Pay::wechat($t_wechat);
        db()->startTrans();
        try{
            $verify = $pay->verify(); // 是的，验签就这么简单！
//            $verify=json_decode('{"appid":"wx39550909a3ba8187","attach":"\u652f\u4ed8\u8ba2\u5355\uff1a201908020933451969_7","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1547877721","nonce_str":"KJvDTNO2yDDUhcRc","openid":"oFJwzwxD5PPdgKJM6BWGuJ8KpR5g","out_trade_no":"201908020933451969_7_1","result_code":"SUCCESS","return_code":"SUCCESS","sign":"18C333B628251A12690F5DD2B03BE604","time_end":"20190802093422","total_fee":"1","trade_type":"APP","transaction_id":"4200000354201908022603531678"}',true);
            db('notify')->insertGetId(array('return'=>json_encode($verify),'pay_type'=>1,'type'=>2,'createtime'=>date('Y-m-d H:i:s'),'pid'=>0));
//            $order1['out_trade_no']=$verify['out_trade_no'];
//            $order1['total_fee']=$verify['total_fee'];
//            $order1['refund_fee']=$verify['total_fee'];
//            $refund =  $pay->refund($order1);
//            dump($refund);die;
            //支付成功
            $order_num=$verify['out_trade_no'];
            $a=explode('_',$order_num);
            foreach($a as $v){
                $len=strlen($v)+1;
                $times=$v;
            }
            $order_num1=substr($order_num,0,-$len);
            $order=db('order')->where(array('o_order_num'=>$order_num1,'o_pay_status'=>0))->find();
            $user=db('user')->where(array('u_id'=>$order['u_id']))->find();
            if($order['o_type']==1){
                $type='配送上门';
            }else if($order['o_type']==2){
                $type='我要自提';
            }
            if(!empty($order)){
                if($order['o_status']==0){
                    $res=db("order")
                        ->where(array("o_id" => $order['o_id']))
                        ->update(array("o_status" => 1,'o_pay_type'=>1,'o_pay_status'=>1,'o_pay_time'=>time()));
                    $system=db('system')->find();
                    $url=$system['order_notice'].'你有新的订单，请及时处理:'.date('Y-m-d-H:i:s',$order['o_create_time']).','.$order['o_id'].','.$user['u_store_name'].',微信,已支付,'.$type.','.$order['o_real_price'].'';
                    $content= file_get_contents($url);
                    db('order_log')->insert(array('o_id'=>$order['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'订单支付成功：微信'));
                }else{
                    $res=db("order")
                        ->where(array("o_id" => $order['o_id']))
                        ->update(array('o_pay_type'=>1,'o_continue_pay_type'=>1,'o_pay_status'=>1,'o_pay_time'=>time()));
                    db('order_log')->insert(array('o_id'=>$order['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'订单支付成功：微信'));
                }
                if($res==false){
                    if($order['o_status']==0){
                        $res=db("order")
                            ->where(array("o_id" => $order['o_id']))
                            ->update(array("o_status" => 1,'o_pay_type'=>1,'o_pay_status'=>1,'o_pay_time'=>time()));
                        $system=db('system')->find();
                        $url=$system['order_notice'].'你有新的订单，请及时处理:'.date('Y-m-d-H:i:s',$order['o_create_time']).','.$order['o_id'].','.$user['u_store_name'].',微信,已支付,'.$type.','.$order['o_real_price'].'';
                        $content= file_get_contents($url);
                        db('order_log')->insert(array('o_id'=>$order['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'订单支付成功：微信'));
                    }else{
                        $res=db("order")
                            ->where(array("o_id" => $order['o_id']))
                            ->update(array('o_pay_type'=>1,'o_continue_pay_type'=>1,'o_pay_status'=>1,'o_pay_time'=>time()));
                        db('order_log')->insert(array('o_id'=>$order['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'订单支付成功：微信'));
                    }
                }
            }else{
                $order1['out_trade_no']=$verify['out_trade_no'];
                $order1['total_fee']=$verify['total_fee'];
                $order1['refund_fee']=$verify['total_fee'];
                $refund =  $pay->refund($order1);
            }
            db()->commit();
        } catch (Exception $e) {
            db()->rollback();
        }
        return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
    }
}